package com.jw.banddroid;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Locale;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.jw.banddroid.bandsintown.ApiParser;
import com.jw.banddroid.bandsintown.Server;
import com.jw.banddroid.bandsintown.Storage;
import com.jw.banddroid.exeptions.ApiServerException;

public class Main extends Activity {

	/**
	 * LocationManager.
	 */
	private LocationManager locationManager = null;

	private EditText city, artist;
	
	private Storage storage;

	/**
	 * The current location with the best accuracy.
	 */
	private Location currentLocation = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Load Views
		RadioGroup radioGroup = (RadioGroup) findViewById(R.id.selection_type_group);
		Button loadMapButton = (Button) findViewById(R.id.button_search);
		artist = (EditText) findViewById(R.id.artist_name);
		city = (EditText) findViewById(R.id.location_city);

		// register listeners
		registerLocationListener();
		radioGroup
				.setOnCheckedChangeListener(createRadioGroupListener(loadMapButton));
		OnClickListener onClickListener = createButtonListener(radioGroup);
		loadMapButton.setOnClickListener(onClickListener);
	}

	/**
	 * Registers this class for location updates from GPS (fine location) and
	 * network (coarse location).
	 */
	private void registerLocationListener() {
		locationManager = (LocationManager) getApplicationContext()
				.getSystemService(Context.LOCATION_SERVICE);

		LocationListener locationListener = new MyLocationListener();

		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
				0, locationListener);
	}

	public class MyLocationListener implements LocationListener {

		@Override
		public void onLocationChanged(Location loc) {

			currentLocation = loc;
		}

		@Override
		public void onProviderDisabled(String provider) {
		}

		@Override
		public void onProviderEnabled(String provider) {
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}

	}

	/**
	 * As soon as the user checks one of the radio buttons, the
	 * "load/don't load"-buttons will be enabled. Additionally, the
	 * lat/lon-EditTexts will be visible/invisible when the user chooses to
	 * insert the coordinate manually.
	 * 
	 * @param loadMapButton
	 *            the "Load!"-button.
	 * @param dontLoadMapButton
	 *            the "Don't load anything"-button.
	 * @param latEdit
	 *            latitude EditText.
	 * @param lonEdit
	 *            longitude EditText.
	 * @return the new created listener.
	 */
	private OnCheckedChangeListener createRadioGroupListener(
			final Button loadMapButton) {
		return new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(final RadioGroup group,
					final int checkedId) {

				LinearLayout artistView = (LinearLayout) findViewById(R.id.artist_selection_layout);
				LinearLayout locationView = (LinearLayout) findViewById(R.id.location_selection_layout);
				loadMapButton.setEnabled(true);

				if (checkedId == R.id.artist) {
					artistView.setVisibility(View.VISIBLE);
				} else {
					artistView.setVisibility(View.GONE);
				}

				if (checkedId == R.id.location) {
					locationView.setVisibility(View.VISIBLE);
				} else {
					locationView.setVisibility(View.GONE);
				}
			}
		};
	}

	/**
	 * Reads the manual coordinate EditTexts and registers the button listeners.
	 * 
	 * @param radioGroup
	 * @param latEdit
	 *            Manual Latitude EditText.
	 * @param lonEdit
	 *            Manual Longitude EditText.
	 */
	private OnClickListener createButtonListener(final RadioGroup radioGroup) {
		return new OnClickListener() {
			@Override
			public void onClick(final View view) {
				try {
					performClick(view.getId(), radioGroup
							.getCheckedRadioButtonId());
				} catch (ApiServerException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
	}

	/**
	 * Do the action when the user clicks a Button. Generates the
	 * {@link BoundingBox} from the coordinate and chosen radius, sets the
	 * resultType (RESULT_OK when a map should be loaded, otherwise false) and
	 * calls {@link #sendResultAndExit(BoundingBox, int)}
	 * 
	 * @param buttonId
	 *            android-id from the clicked Button.
	 * @param checkedRadioButtonId
	 *            android-id from the checked RadioButton.
	 * @param lat
	 *            latitude from the EditText.
	 * @param lon
	 *            longitude from the EditText.
	 * @throws IOException
	 * @throws ApiServerException
	 * @throws SAXException
	 */
	private void performClick(final int buttonId, final int checkedRadioButtonId)
			throws ApiServerException, IOException, SAXException {

		switch (checkedRadioButtonId) {
		case R.id.artist:
			String band = artist.getText().toString();
			getLocationResult(band);
			break;
		case R.id.location:
			String loc = city.getText().toString();
			getLocationResult(loc);
		case R.id.current_location:
			// getCurrLocationResult();
			break;
		}
	}

	private void getArtistResult(String artist) {

	}

	private void getLocationResult(String loc) throws ApiServerException,
			IOException, SAXException {

		Server server = new Server();

		final InputSource in = new InputSource(new InputStreamReader(server.getStreamForLocation(loc), "UTF-8"));
		
		ApiParser apiParser = new ApiParser();
		
		apiParser.parseDocument(in);
		
		storage = apiParser.getStorage();
		
		Intent result = new Intent(this, Result.class);
		
		startActivity(result);  

	}

	private void getCurrLocationResult() {
		double lat = currentLocation.getLatitude();
		double lon = currentLocation.getLongitude();

		try {
			Geocoder myLocation = new Geocoder(getApplicationContext(), Locale
					.getDefault());
			List<Address> myList = myLocation.getFromLocation(lat, lon, 1);

		} catch (IOException e) { e.printStackTrace(); }
	}
}